/**
 * jims.
 */
package com.jims.api.v1.controller.sys;


import com.jims.master.common.data.Message;
import com.jims.master.common.data.StringData;
import com.jims.master.common.utils.*;
import com.jims.master.common.web.BaseController;

import com.jims.master.modules.base.user.entity.MasterBaseinfo;
import com.jims.master.modules.base.user.entity.MasterContactinfo;
import com.jims.master.modules.base.user.entity.MasterDoctorinfo;
import com.jims.master.modules.base.user.service.MasterBaseinfoService;
import com.jims.master.modules.base.user.service.MasterDoctorinfoService;
import com.jims.master.modules.sys.entity.SysLoginName;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.security.UsernamePasswordToken;
import com.jims.master.modules.sys.service.*;
import com.jims.master.modules.sys.utils.UserUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录Controller
 * @author WangYq
 * @version 2017-5-15
 */
@Controller
@RequestMapping(value = "/login")
public class LoginController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private SysLoginNameService sysLoginNameService;
	@Autowired
	private UserService userService;
	@Autowired
	private MasterBaseinfoService masterBaseinfoService;
	@Autowired
	private MasterDoctorinfoService masterDoctorinfoService;
	/**
	 * @Title: validateEistenceV100
	 * @Description: （验证手机号是否存在）
	 * @param mobile
	 * @return java.lang.String
	 * @author WangYQ
	 * @date 2017-11-17
	 * @throws
	 */
	@RequestMapping(value = "V100/validateEistence",method ={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public String validateEistence(@RequestParam(required=true) String mobile,HttpServletRequest request,HttpServletResponse response) {
		Message msg=new Message();
		String userId=sysLoginNameService.findValidate(mobile);
		if(userId==null||userId.equals("")){
			msg.setErrCode("414");
			msg.setErrMsg("您输入的手机号码不存在");
		}else{
			msg.setStatus("200");
		}
		return SecurityUtil.encryptMsgData(msg);
	}

	/**
	 * @Title: checkCodeMethodV100
	 * @Description: （验证码登录）
	 * @param mobile
	 * @param mobileCode
	 * @return java.lang.String
	 * @author WangYQ
	 * @date 2017-11-19
	 * @throws
	 */
	@RequestMapping(value = "V100/loginCheckCodeMethod",method ={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	private String loginCheckCodeMethod(@RequestParam(required=true) String mobile,@RequestParam(required=true) String mobileCode,@RequestParam(required=true)String userType,HttpServletRequest request,HttpServletResponse response){
		Message msg=new Message();
		if(getUserId(mobile)==null||getUserId(mobile).equals("")){
			msg.setStatus("414");
			msg.setErrCode("414");
			msg.setErrMsg("您输入的手机号码不存在");
			return SecurityUtil.encryptMsgData(msg);
		}
		if("1".equals(getUserType(mobile))){
			msg.setStatus("414");
			msg.setErrCode("414");
			msg.setErrMsg("无权在该端口登录");
			return SecurityUtil.encryptMsgData(msg);
		}
		Factory<SecurityManager> factory = new IniSecurityManagerFactory();
		// 2、得到SecurityManager实例并绑定给SecurityUtils
		org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
		SecurityUtils.setSecurityManager(securityManager);
		UsernamePasswordToken upToken = new UsernamePasswordToken();
		upToken.setUsername(mobile);
		upToken.setUserType(userType);
		upToken.setMobileCode(mobileCode);
//		upToken.setUserType(userType);
		upToken.setType("3");
		upToken.setHost(request.getRemoteHost());
		Subject subject = SecurityUtils.getSubject();
		try{
			// 4、登录，即身份验证
			subject.login(upToken);
		} catch (AuthenticationException e) {
			// 5、身份验证失败
			logger.info("用户身份验证失败");
		}
		if (subject.isAuthenticated()) {
			msg.setStatus("200");
//			MasterBaseinfo masterBaseinfo=UserUtils.getBaseinfo(UserUtils.getUser().getPersionId());
			User user=userService.get(sysLoginNameService.findValidate(mobile));
			MasterBaseinfo masterBaseinfo=null;
			if(user.getPersionId()!=null && !user.getPersionId().equals("")){
				masterBaseinfo=masterBaseinfoService.get(user.getPersionId());
			}
			msg.setData(masterBaseinfo);
		} else {
			msg.setErrCode("414");
			msg.setErrMsg("验证码有误，请重新填写");
		}
		return SecurityUtil.encryptMsgData(msg);
	}
	/**
	 * @Title: loginV100
	 * @Description: （手机号加密码登录验证）
	 * @param mobile
	 * @param password
	 * @return java.lang.String
	 * @author WangYQ
	 * @date 2017-11-19
	 * @throws
	 */
	@RequestMapping(value = "V100/passwordLogin",method ={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public String passwordLogin(@RequestParam(required=true) String mobile,@RequestParam(required=true) String password,@RequestParam(required=true) String userType,String payOpenid,HttpServletRequest request,HttpServletResponse response) {
		UserUtils.clearCache(UserUtils.getUser());
		UserUtils.getSubject().logout();
		Message msg=new Message();
		if(getUserId(mobile)==null||getUserId(mobile).equals("")){
			msg.setStatus("414");
			msg.setErrCode("414");
			msg.setErrMsg("您输入的手机号码不存在");
			return SecurityUtil.encryptMsgData(msg);
		}
		if("1".equals(getUserType(mobile))){
			msg.setStatus("414");
			msg.setErrCode("414");
			msg.setErrMsg("无权在该端口登录");
			return SecurityUtil.encryptMsgData(msg);
		}

		Factory<SecurityManager> factory = new IniSecurityManagerFactory();
		// 2、得到SecurityManager实例并绑定给SecurityUtils
		org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
		SecurityUtils.setSecurityManager(securityManager);
		UsernamePasswordToken upToken = new UsernamePasswordToken();
		upToken.setUsername(mobile);
		upToken.setPassword(password.toCharArray());
//		upToken.setUserType(userType);
		upToken.setHost(request.getRemoteHost());
		Subject subject = SecurityUtils.getSubject();
		try{
			// 4、登录，即身份验证
			subject.login(upToken);
		} catch (AuthenticationException e) {
			// 5、身份验证失败
			logger.info("用户身份验证失败");
			e.printStackTrace();
		}
		if (subject.isAuthenticated()) {
			msg.setStatus("200");
//			User user=UserUtils.getUser();
			User user=userService.get(sysLoginNameService.findValidate(mobile));
			if(payOpenid!=null&&!payOpenid.equals("")){
				user.setPayOpenid(payOpenid);
				userService.updateOpenid(user);
			}
			MasterBaseinfo masterBaseinfo=null;
			if(user.getPersionId()!=null && !user.getPersionId().equals("")){
				masterBaseinfo=masterBaseinfoService.get(user.getPersionId());
				if(masterBaseinfo!=null){
					MasterDoctorinfo masterDoctorinfo=masterDoctorinfoService.getDoctorinfoByBaseinfoId(masterBaseinfo.getId());
					masterBaseinfo.setMasterDoctorinfo(masterDoctorinfo);
				}

			}
			msg.setData(masterBaseinfo);
			logger.debug("登录手机号码："+mobile);
			CacheUtils.put("mobile"+mobile,mobile);
			return SecurityUtil.encryptMsgData(msg);
		} else {
			msg.setErrCode("414");
			msg.setErrMsg("非常抱歉！您输入手机号与密码有误");
			return SecurityUtil.encryptMsgData(msg);
		}
	}


	/**
	 * @Title: chagePasswordV100
	 * @Description: （修改密码）
	 * @param mobile
	 * @param password
	 * @return java.lang.String
	 * @author WangYQ
	 * @date 2017-12-05
	 * @throws
	 */
	@RequestMapping(value = "V100/chagePassword",method ={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public String chagePassword(@RequestParam(required=true)String mobile,@RequestParam(required=true)String password,HttpServletRequest request, HttpServletResponse response){
		Message msg=new Message();
		int i=sysLoginNameService.retrievePassword(mobile,password);
		if(i==0){
			msg.setStatus("0");
			msg.setErrCode("414");
			msg.setErrMsg("修改密码失败");
		}else{
			msg.setData("修改密码成功");
		}
		return SecurityUtil.encryptMsgData(msg);
	}
	/**
	 * @Title: consumerLogoutV100
	 * @Description: （登出）
	 * @return java.lang.String
	 * @author WangYQ
	 * @date 2017-12-05
	 * @throws
	 */

	@RequestMapping(value = "V100/consumerLogout",method ={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public String consumerLogout() {
		Message msg=new Message();
		UserUtils.clearCache(UserUtils.getUser());
		UserUtils.getSubject().logout();
		return SecurityUtil.encryptMsgData(msg);
	}

	/**
	 * @Title: wxCheckCodeV100
	 * @Description: （验证微信是否绑定）
	 * @param openid
	 * @return java.lang.String
	 * @author WangYQ
	 * @date 2017-12-16
	 * @throws
	 */
	@RequestMapping(value = "V100/wxCheckCode",method ={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public String wxCheckCode(@RequestParam(required=true) String openid,String userType,String loginType,HttpServletRequest request, HttpServletResponse response){
		Message msg=new Message();
		User user =userService.findUserByOpenid(openid);
		if(user ==null){
			msg.setStatus("0");
			msg.setErrCode("414");
			msg.setErrMsg("您还没用进行微信绑定登录，请输入手机号进行绑定");
		}else{
			User loginUser=new User();
			loginUser.setCurrentLogin(user.getCurrentLogin());
			loginUser.setPassword(user.getPassword());
			loginUser.setUserType(user.getUserType());
			msg.setData(loginUser);
		}
		return SecurityUtil.encryptMsgData(msg);
	}
	/**
	 * 获取userType
	 * @param  mobile
	 * @return String
	 */
	public String getUserType(String mobile) {
		String userId=getUserId(mobile);
		User user=userService.get(userId);
		return user.getUserType();
	}
	/**
	 * 获取userId
	 * @param  mobile
	 * @return String
	 */
	public String getUserId(String mobile) {
		String userId=sysLoginNameService.findValidate(mobile);
		return userId;
	}

}
